package org.zj.webview.app.filter;

import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Filter;
import org.noear.solon.core.handle.FilterChain;
import org.zj.webview.app.config.HttpRandomAccessTokenConfig;

import javax.swing.plaf.PanelUI;

/**
 * 为了防止外部访问，做拦截
 *
 * @author zj
 * @since 2025/7/27
 */
@Component(index = Integer.MIN_VALUE)
public class AppFilter implements Filter {

    /**
     * 访问令牌的名称
     */
    public static final String TOKEN_KEY = "WEBVIEW2-TOKEN";

    private final String token;

    public AppFilter(HttpRandomAccessTokenConfig config) {
        this.token = config.getToken();
    }

    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
        String path = ctx.path();
        if ("/".equals(path)) {
            ctx.redirect("/index.html");
            return;
        }
        String token = ctx.cookie(TOKEN_KEY);
        if (!this.token.equals(token)) {
            ctx.close();
            return;
        }
        chain.doFilter(ctx);
    }
}
